<script setup lang="ts">
import { ref, PropType } from 'vue'
import { Plus, Minus, Grid } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import {
  getInvestigate,
  createInvestigate,
  updateInvestigate,
  deleteInvestigate,
  getInvestigateItemOpinonPage,
  updateInvestigateItemOpinion,
  deleteInvestigateItemOpinion
} from '@/api/cms/investigate'
import LabelTip from '@/components/cms/LabelTip.vue'
import DialogForm from '@/components/cms/DialogForm.vue'
import { dateFormatter } from '@/utils/formatTime'
const { t } = useI18n()
defineOptions({
  name: 'InvestigateForm'
})
defineProps({
  modelValue: { type: Boolean, required: true },
  beanId: { type: String, default: null },
  beanIds: { type: Array as PropType<string[]>, required: true }
})
defineEmits({ 'update:modelValue': null, finished: null })
const focus = ref<any>()
const values = ref<any>({})

let optionIndex = -1
const addNewLine = (index: number) => {
  optionIndex -= 1
  values.value.items.splice(index, 0, {
    id: optionIndex,
    isMultiple: false,
    isQa: false,
    title: '',
    options: [{ id: -1, title: '', optionCount: 0 }]
  })
}
let itemOptionIndex = -1
const addOptionNewLine = (itemIndex: number, index: number) => {
  console.log('index->', index)
  itemOptionIndex -= 1
  values.value.items[itemIndex].options.splice(index, 0, {
    id: itemOptionIndex,
    optionCount: 0,
    title: ''
  })
}

//问题意见
const itemOpinionDialogVisible = ref<boolean>(false)
const itemOpinionQueryParams = reactive({
  investigateItemId: 0,
  pageNo: 1,
  pageSize: 20
})
const tableLayout = ref('auto')
const opinionLoading = ref(true) // 列表的加载中
const opinionTotal = ref(0) // 列表的总页数
const opinionDatas = ref([]) // 列表的数据
const opinionTableRef = ref() // 表格的 Ref
/** 查询意见列表 */
const getInvestigateItemOpinons = async () => {
  opinionLoading.value = true
  try {
    const data = await getInvestigateItemOpinonPage(itemOpinionQueryParams)
    opinionDatas.value = data.list
    opinionTotal.value = data.total
  } finally {
    opinionLoading.value = false
  }
}
//点击新选项查询
const handleOpinionQuery = async (id: number) => {
  itemOpinionQueryParams.investigateItemId = id
  itemOpinionDialogVisible.value = true
  await getInvestigateItemOpinons()
}

//修改和删除后查询
const handleOpinionQueryList = async () => {
  itemOpinionDialogVisible.value = true
  await getInvestigateItemOpinons()
}

const handleItemOpinionUpdate = async (id: number, itemAnswer: string) => {
  await updateInvestigateItemOpinion({ id, itemAnswer })
  handleOpinionQueryList()
}

const handleItemOpinionDel = async (id: number) => {
  await deleteInvestigateItemOpinion(id)
  handleOpinionQueryList()
}
</script>

<template>
  <dialog-form
    v-model:values="values"
    :name="$t('cms.menu.interact.investigate')"
    :query-func="getInvestigate"
    :create-func="createInvestigate"
    :update-func="updateInvestigate"
    :delete-func="deleteInvestigate"
    :bean-id="beanId"
    :bean-ids="beanIds"
    :focus="focus"
    :init-values="
      () => ({
        investigateMode: 1,
        investigateInterval: 0,
        total: 0,
        enabled: true,
        sortNum: 10,
        items: [
          {
            id: -1,
            title: '',
            isMultiple: false,
            isQa: false,
            options: [{ id: -1, title: '', optionCount: 0 }]
          }
        ]
      })
    "
    :to-values="(bean) => ({ ...bean })"
    :model-value="modelValue"
    perms="investigate"
    large
    @update:model-value="(event) => $emit('update:modelValue', event)"
    @finished="() => $emit('finished')"
  >
    <template #default="{}">
      <el-row>
        <el-col :span="24">
          <el-form-item
            prop="title"
            :rules="{ required: true, message: () => $t('common.required') }"
          >
            <template #label><label-tip message="cms.investigate.title" /></template>
            <el-input ref="focus" v-model="values.title" maxlength="300" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="description">
            <template #label><label-tip message="cms.investigate.description" /></template>
            <el-input v-model="values.description" type="textarea" :rows="3" maxlength="300" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="beginDate">
            <template #label><label-tip message="cms.investigate.beginDate" help /></template>
            <el-date-picker v-model="values.beginDate" type="datetime" class="w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="endDate">
            <template #label><label-tip message="cms.investigate.endDate" help /></template>
            <el-date-picker v-model="values.endDate" type="datetime" class="w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            prop="investigateMode"
            :rules="{ required: true, message: () => $t('common.required') }"
          >
            <template #label><label-tip message="cms.investigate.mode" help /></template>
            <el-select v-model="values.investigateMode" class="w-full"
              ><el-option
                v-for="n in [1, 2, 3]"
                :key="n"
                :value="n"
                :label="$t(`cms.vote.mode.${n}`)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="createTime">
            <template #label><label-tip message="cms.investigate.created" /></template>
            <el-date-picker v-model="values.createTime" type="createTime" class="w-full" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            prop="investigateInterval"
            :rules="{ required: true, message: () => $t('common.required') }"
          >
            <template #label><label-tip message="cms.investigate.interval" help /></template>
            <el-input-number
              v-model="values.investigateInterval"
              :min="0"
              :max="32767"
              class="w-48"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            prop="sortNum"
            :rules="{ required: true, message: () => $t('common.required') }"
          >
            <template #label><label-tip message="cms.investigate.sortNum" help /></template>
            <el-input-number v-model="values.sortNum" :min="0" :max="32767" class="w-48" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="enabled">
            <template #label><label-tip message="cms.investigate.enabled" /></template>
            <el-switch v-model="values.enabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="joinNum">
            <template #label><label-tip message="cms.investigate.joinNum" /></template>
            <el-input-number :model-value="values.joinNum" disabled class="w-48" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <template #label><label-tip message="cms.investigate.items" /></template>
            <div class="w-full table-auto border-slate-450">
              <draggable
                v-model="values.items"
                :animation="250"
                tag="div"
                handle=".draggable-handle"
                item-key="id"
              >
                <template #item="{ element: item, index }">
                  <div>
                    <div class="flex items-center my-4">
                      <el-icon class="text-2xl align-middle cursor-move draggable-handle"
                        ><Grid
                      /></el-icon>
                      <el-button
                        class="ml-3"
                        :icon="Plus"
                        circle
                        @click="() => addNewLine(index + 1)"
                      />
                      <el-button
                        :disabled="values.items.length <= 1"
                        :icon="Minus"
                        circle
                        @click="
                          () => (values.items = values.items.filter((it) => it.id !== item.id))
                        "
                      />
                      <el-form-item
                        class="ml-2 grow"
                        :prop="`items.${index}.title`"
                        :rules="{ required: true, message: () => $t('common.required') }"
                      >
                        <el-input v-model="item.title" maxlength="300" />
                      </el-form-item>
                      <el-form-item class="ml-2 grow">
                        <el-checkbox v-model="item.isMultiple">
                          {{ t('cms.investigate.item.isMultiple') }}</el-checkbox
                        >
                        <el-checkbox v-model="item.isQa">
                          {{ t('cms.investigate.item.isQa') }}
                        </el-checkbox>
                        <el-button
                          type="primary"
                          text
                          :disabled="!item.isQa"
                          @click="handleOpinionQuery(item.id)"
                          >{{ t('cms.investigate.item.opinion') }}
                        </el-button>
                      </el-form-item>
                    </div>
                    <div v-if="!item.isQa" class="ml-20">
                      <draggable
                        v-model="item.options"
                        :animation="250"
                        tag="div"
                        handle=".draggable-handle"
                        item-key="id"
                      >
                        <template #item="{ element: itemOption, index: k }">
                          <div class="flex items-center my-4">
                            <el-icon class="text-2xl align-middle cursor-move draggable-handle"
                              ><Grid
                            /></el-icon>
                            <el-button
                              class="ml-3"
                              :icon="Plus"
                              circle
                              @click="() => addOptionNewLine(index, k + 1)"
                            />
                            <el-button
                              :disabled="item.options.length <= 1"
                              :icon="Minus"
                              circle
                              @click="
                                () =>
                                  (item.options = item.options.filter(
                                    (it) => it.id !== itemOption.id
                                  ))
                              "
                            />
                            <el-form-item
                              class="ml-2 grow"
                              :prop="`items.${index}.options.${k}.title`"
                              :rules="{
                                required: true,
                                message: () => $t('common.required')
                              }"
                            >
                              <el-input v-model="itemOption.title" maxlength="300" />
                            </el-form-item>
                            <el-form-item class="ml-2 grow">
                              <el-input-number
                                v-model="itemOption.optionCount"
                                :min="0"
                                :max="2147483647"
                                class="w-48"
                              />
                            </el-form-item>
                          </div>
                        </template>
                      </draggable> </div
                  ></div>
                </template>
              </draggable>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </dialog-form>
  <!--问题意见弹框-->
  <Dialog v-model="itemOpinionDialogVisible" :title="t('cms.investigate.item.opinion')" width="50%">
    <ContentWrap>
      <el-table
        v-loading="opinionLoading"
        :table-layout="tableLayout"
        :data="opinionDatas"
        ref="opinionTableRef"
        row-key="id"
      >
        <el-table-column label="内容" align="center" prop="itemAnswer">
          <template #default="{ row }">
            <el-input v-model="row.itemAnswer" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
        />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <XTextButton
              preIcon="ep:delete"
              :title="t('action.del')"
              @click="handleItemOpinionDel(row.id)"
            />
            <XTextButton
              preIcon="ep:delete"
              :title="t('action.update')"
              @click="handleItemOpinionUpdate(row.id, row.itemAnswer)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="opinionTotal"
        v-model:page="itemOpinionQueryParams.pageNo"
        v-model:limit="itemOpinionQueryParams.pageSize"
        @pagination="getInvestigateItemOpinons"
      />
    </ContentWrap>
  </Dialog>
</template>
